from typing import List
from .model import Numberrange
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    number_current: str = Field(None, alias='number_current')    
    number_to: str = Field(None, alias='number_to')    
    number_from: str = Field(None, alias='number_from')    
    number_prefix: str = Field(None, alias='number_prefix')    
    range_id: str = Field(None, alias='range_id')


# 设置请求接收字段
class NumberrangeSchemaIn(ModelSchema):

    class Config:
        model = Numberrange
        model_exclude = ['create_datetime', 'update_datetime', 'belong_dept', 'modifier', 'creator', 'id']


# 设置响应字段
class NumberrangeSchemaOut(ModelSchema):

    class Config:
        model = Numberrange
        model_fields = '__all__'


# 创建Numberrange
@router.post('/numberrange', response=NumberrangeSchemaOut)
def create_numberrange(request, data: NumberrangeSchemaIn):
    numberrange = create(request, data, Numberrange)
    return numberrange


# 删除Numberrange
@router.delete('/numberrange/{id}')
def delete_numberrange(request, id: int):
    delete(id, Numberrange)
    return {'success': True}


# 更新Numberrange
@router.put('/numberrange/{id}', response=NumberrangeSchemaOut)
def update_numberrange(request, id: int, data: NumberrangeSchemaIn):
    numberrange = update(request, id, data, Numberrange)
    return numberrange


# 获取Numberrange
@router.get('/numberrange', response=List[NumberrangeSchemaOut])
@paginate(MyPagination)
def list_numberrange(request, filters: Filters = Query(...)):
    qs = retrieve(request, Numberrange, filters)
    return qs


# 导入
@router.get('/numberrange/all/export')
def export_numberrange(request):
    export_fields = ('number_current', 'number_to', 'number_from', 'number_prefix', 'range_id', )
    return export_data(request, Numberrange, NumberrangeSchemaOut, export_fields)


# 导出
@router.post('/numberrange/all/import')
def import_numberrange(request, data: ImportSchema):
    import_fields = ('number_current', 'number_to', 'number_from', 'number_prefix', 'range_id', )
    return import_data(request, Numberrange, NumberrangeSchemaIn, data, import_fields)
    